/**
 * 
 */
package test.print;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

import org.apache.commons.collections.CollectionUtils;

/**
 * @author MTorres
 *
 */
public class V3PrintServiceImpl implements test.print.V3PrintService {
	private static final Map papersizeMap = new HashMap();
	
	
	
	public V3PrintServiceImpl() {
		super();
		papersizeMap.put(PAPER_LETTER, new Dimension((int)Math.ceil(awtInchToPixels(8.5)) ,(int)Math.ceil(awtInchToPixels(11) )));
		papersizeMap.put(PAPER_LEGAL, new Dimension((int)Math.ceil(awtInchToPixels(8.5)) ,(int)Math.ceil(awtInchToPixels(14) )));
		papersizeMap.put(PAPER_BANNER, new Dimension((int)Math.ceil(awtInchToPixels(11)) ,(int)Math.ceil(awtInchToPixels(17) )));
	}



	/* (non-Javadoc)
	 * @see com.vitechinc.v3.core.services.PrintService#getDimension(java.lang.String)
	 */
	public Dimension getDimension(String paperCode) {				
		Dimension dim= (Dimension)papersizeMap.get(paperCode);
		if (dim==null)dim =(Dimension) papersizeMap.get(PAPER_LETTER);
		return dim;
	}

	public static double awtInchToPixels(double inch){
		return inch*72;
	}
	
	public static double awtPixelsToInch(double pixels){
		return pixels/72;
	}
	
	public Map getAvailablePrinters(){
		final Map printers = new LinkedHashMap();
		
		PrintService printServices[] = findAllPrintServices();
		
		for (int i = 0; i < printServices.length; i++) 
			printers.put(printServices[i].getName(), printServices[i].getName());
		
		return printers;
	}
	
	/**
	 *  
	 * @param printerName
	 * @return requestes printer service when found or null. Default service is returned when printerName is null
	 */
	public PrintService getPrintService(String printerName){
		PrintService[] printServices = findAllPrintServices();
		for (int i = 0; i < printServices.length; i++)
		{
			if (printServices[i].getName().equals(printerName))
				return printServices[i];
		}
		return null;
	}
	
	public List getAvailablePrintersAsList() {
		List ret = new ArrayList();
		PrintService[] services= findAllPrintServices();
		if (services!=null){
			CollectionUtils.addAll(ret, services);
		}
		return ret;
	}
	
	private PrintService[] findAllPrintServices(){
		return PrintServiceLookup.lookupPrintServices(null, null);
	}
}
